package com.centaline.androidsalesblog.activities.sale;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetBehavior;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatTextView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewStub;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.android.volley.VolleyError;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.navi.BaiduMapNavigation;
import com.baidu.mapapi.navi.NaviParaOption;
import com.bumptech.glide.DrawableRequestBuilder;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.activities.entrust.ReservationListActivity;
import com.centaline.androidsalesblog.activities.map.AroundMapActivity;
import com.centaline.androidsalesblog.activities.mine.BindingPhoneActivity;
import com.centaline.androidsalesblog.activities.mine.LoginActivity;
import com.centaline.androidsalesblog.activities.news.ChatActivity;
import com.centaline.androidsalesblog.api.sale.PostDetailApi;
import com.centaline.androidsalesblog.application.MyLocation;
import com.centaline.androidsalesblog.base.BaseActivity;
import com.centaline.androidsalesblog.constants.AppConstant;
import com.centaline.androidsalesblog.constants.AppNameType;
import com.centaline.androidsalesblog.constants.CommonConstant;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.constants.SourceType;
import com.centaline.androidsalesblog.constants.SprfConstant;
import com.centaline.androidsalesblog.events.MineInfoUpdate;
import com.centaline.androidsalesblog.events.ReserveUpdate;
import com.centaline.androidsalesblog.iml.ImgViewPagerClickListener;
import com.centaline.androidsalesblog.iml.StaffItemDetailOnClick;
import com.centaline.androidsalesblog.model.businissobject.CollectInfoBo;
import com.centaline.androidsalesblog.model.businissobject.PostDetailBo;
import com.centaline.androidsalesblog.model.businissobject.PostImgBo;
import com.centaline.androidsalesblog.model.businissobject.RentalBo;
import com.centaline.androidsalesblog.model.businissobject.ShareBo;
import com.centaline.androidsalesblog.model.databaseobject.BizUnitDo;
import com.centaline.androidsalesblog.model.databaseobject.StaffDo;
import com.centaline.androidsalesblog.model.databaseobject.UserDo;
import com.centaline.androidsalesblog.model.responseobject.CollectInfoListRo;
import com.centaline.androidsalesblog.model.responseobject.PostDetailRo;
import com.centaline.androidsalesblog.model.responseobject.ReservationRo;
import com.centaline.androidsalesblog.model.responseobject.SimpleUserCenterRo;
import com.centaline.androidsalesblog.rx.database.RxDataBase;
import com.centaline.androidsalesblog.rx.map.RxMap;
import com.centaline.androidsalesblog.rx.request.RxRequest;
import com.centaline.androidsalesblog.utils.BdMapUtil;
import com.centaline.androidsalesblog.utils.CentaDistanceUtil;
import com.centaline.androidsalesblog.utils.ContactUtil;
import com.centaline.androidsalesblog.utils.DateUtil;
import com.centaline.androidsalesblog.utils.PriceUtil;
import com.centaline.androidsalesblog.utils.ResponseCheck;
import com.centaline.androidsalesblog.utils.RongUserIdUtil;
import com.centaline.androidsalesblog.widgets.ConsultView;
import com.centaline.androidsalesblog.widgets.DetailImgLayout;
import com.centaline.androidsalesblog.widgets.DetailToolsView;
import com.centaline.androidsalesblog.widgets.FlowLayout;
import com.centaline.androidsalesblog.widgets.ShareDialog;
import com.centaline.androidsalesblog.widgets.dropdown.SpecialLoadView;
import com.centanet.framework.glide.GlideLoad;
import com.centanet.framework.interfaces.IResponseListener;
import com.centanet.framework.utils.SprfUtil;
import com.centanet.framework.widget.AbstractSpecialLoadView;
import com.orhanobut.logger.Logger;
import com.trello.rxlifecycle.ActivityEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Locale;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;


/**
 * 租房详情
 */
public class RentDetailActivity extends BaseActivity implements View.OnClickListener {

    private SpecialLoadView specialLoadView;
    private AppCompatTextView atv_price, atv_house_type, atv_area, atv_floor,
            atv_orientations, atv_fitment, atv_build_year, atv_esf_estate,
            atv_rent_type, atv_pay_type, atv_address, atv_map_name, atv_nav, atv_num_price, atv_num_nearby;
    private ImageView img_arrow_address, img_map;
    private DetailImgLayout detailImgLayout;
    private ViewStub vs_sale_metro, vs_appliance, vs_tools;
    private RelativeLayout rl_map;
    private View overView;
    private ConsultView consultView;
    private BottomSheetBehavior bottomSheetBehavior;
    private DetailToolsView detailToolsView;

    private DrawableRequestBuilder<String> requestBuilder;
    private ArrayList<PostImgBo> postImgBoArrayList = new ArrayList<>();
    private ArrayList<String> imgList = new ArrayList<>();//小图列表
    private ArrayList<String> imgListH = new ArrayList<>();//大图列表
    private PostDetailApi postDetailApi;
    private PostDetailBo postDetailBo;
    private String postId;

    private boolean collect;//是否收藏
    private String collectId;
    private LocationClient locationClient;

    private String shareUrl;
    private ShareDialog shareDialog;
    private String userPhone;
    private int refreshTag = 0;//0.不刷新 1.加约看 2.查看约看单

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    protected int setLayoutId() {
        return R.layout.activity_rent_detail;
    }

    @Override
    protected void findViews() {
        setUniversalToolbar();
        specialLoadView = (SpecialLoadView) findViewById(R.id.specialLoadView);
        atv_price = (AppCompatTextView) findViewById(R.id.atv_price);
        atv_rent_type = (AppCompatTextView) findViewById(R.id.atv_rent_type);
        atv_pay_type = (AppCompatTextView) findViewById(R.id.atv_pay_type);
        atv_house_type = (AppCompatTextView) findViewById(R.id.atv_house_type);
        atv_area = (AppCompatTextView) findViewById(R.id.atv_area);
        atv_floor = (AppCompatTextView) findViewById(R.id.atv_floor);
        atv_orientations = (AppCompatTextView) findViewById(R.id.atv_orientations);
        atv_fitment = (AppCompatTextView) findViewById(R.id.atv_fitment);
        atv_build_year = (AppCompatTextView) findViewById(R.id.atv_build_year);
        atv_esf_estate = (AppCompatTextView) findViewById(R.id.atv_esf_estate);
        atv_address = (AppCompatTextView) findViewById(R.id.atv_address);
        img_arrow_address = (ImageView) findViewById(R.id.img_arrow_address);
        atv_map_name = (AppCompatTextView) findViewById(R.id.atv_map_name);
        atv_nav = (AppCompatTextView) findViewById(R.id.atv_nav);
        img_map = (ImageView) findViewById(R.id.img_map);
        detailImgLayout = (DetailImgLayout) findViewById(R.id.detailImgLayout);
        vs_sale_metro = (ViewStub) findViewById(R.id.vs_sale_metro);
        atv_num_price = (AppCompatTextView) findViewById(R.id.atv_num_price);
        atv_num_nearby = (AppCompatTextView) findViewById(R.id.atv_num_nearby);
        rl_map = (RelativeLayout) findViewById(R.id.rl_map);
        vs_appliance = (ViewStub) findViewById(R.id.vs_appliance);
        vs_tools = (ViewStub) findViewById(R.id.vs_tools);
        overView = findViewById(R.id.overView);
        consultView = (ConsultView) findViewById(R.id.consultView);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void initViews() {
        requestBuilder = GlideLoad.init(this);
        detailImgLayout.setRequestBuilder(requestBuilder);
        detailImgLayout.setImgViewPagerClickListener(new ImgViewPagerClickListener() {
            @Override
            public void imgItemClick(int position) {
                startActivity(new Intent(RentDetailActivity.this, PostImgListBrowseActivity.class)
                        .putExtra(ExtraConstant.IMG_LIST, imgListH)
                        .putExtra(ExtraConstant.IMG_LIST_THUMBNAIL, imgList)
                        .putExtra(ExtraConstant.IMG_POS, position)
                        .putExtra(PostImgListBrowseActivity.POST_IMG_LIST, postImgBoArrayList));
            }
        });
        specialLoadView.setLoadStatusListener(new AbstractSpecialLoadView.LoadStatusListener() {
            @Override
            public void load() {
                mainRequest();
            }
        });
        consultView.initRequestBuilder(GlideLoad.initRound(this), new StaffItemDetailOnClick() {
            @Override
            public void onClick(final StaffDo staffDo, int tag, String imContent, String msgContent) {
                switch (tag) {
                    case 0:
                        startActivity(new Intent(RentDetailActivity.this, StaffDetailActivity.class)
                                .putExtra(ExtraConstant.StaffNo, staffDo.getStaffNo()));
                        break;
                    case 1:
                        startActivity(new Intent(RentDetailActivity.this, ChatActivity.class)
                                .putExtra(ExtraConstant.TargetId, RongUserIdUtil.getSatffId(staffDo.getStaffNo()))
                                .putExtra(ExtraConstant.MessageTarget, 2)
                                .putExtra(ExtraConstant.MessageTargetValue, postId)
                                .putExtra(ExtraConstant.MessageCome, imContent));
                        baiduEvent("E3_3_Click");
                        break;
                    case 2:
                        ContactUtil.sendMsg(RentDetailActivity.this, staffDo.getMobile(), msgContent);
                        baiduEvent("E3_4_Click");
                        break;
                    case 3:
                        new AlertDialog.Builder(RentDetailActivity.this)
                                .setMessage(String.format(Locale.CHINA, "拨打:%s,%s",
                                        staffDo.getBigCode(), staffDo.getExtCode()))
                                .setPositiveButton("拨打", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        ContactUtil.dial(RentDetailActivity.this, staffDo.getBigCode(), staffDo.getExtCode());
                                        baiduEvent("E3_2_Click");
                                    }
                                }).setNegativeButton("取消", null)
                                .create()
                                .show();
                        break;
                    default:
                        break;
                }
                if (tag != 0) {
                    RxDataBase.saveStaff(staffDo)
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .compose(RentDetailActivity.this.<Void>bindUntilEvent(ActivityEvent.DESTROY))
                            .subscribe(new Action1<Void>() {
                                @Override
                                public void call(Void aVoid) {

                                }
                            });
                }
            }
        });
        bottomSheetBehavior = BottomSheetBehavior.from(consultView);
        bottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
                Logger.d("slideOffset : %s", slideOffset);
                overView.setAlpha(slideOffset);
                overView.setVisibility(slideOffset > 0 ? View.VISIBLE : View.GONE);
            }
        });
        postDetailApi = new PostDetailApi(RentDetailActivity.class, PostDetailRo.class,
                new IResponseListener<PostDetailRo>() {
                    @Override
                    public void onResponse(PostDetailRo postDetailRo) {
                        if (ResponseCheck.check(postDetailRo)) {
                            specialLoadView.loadSuccess();
                            postDetailBo = postDetailRo.getPostDetailBo();
                            setData();
                        } else {
                            specialLoadView.loadError();
                        }
                    }

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        specialLoadView.loadError();
                    }
                });
        postId = getIntent().getStringExtra(ExtraConstant.PostId);
        postDetailApi.setPostId(postId);
        locationClient = MyLocation.getLocationClient();
        RxMap.location(locationClient, false)
                .compose(this.<BDLocation>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<BDLocation>() {
                    @Override
                    public void call(BDLocation bdLocation) {
                        cancelLoadingDialog();
                        switch (bdLocation.getLocType()) {
                            case 61:
                            case 161:
                                NaviParaOption naviParaOption = new NaviParaOption();
                                naviParaOption.startPoint(new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude()))
                                        .endPoint(new LatLng(postDetailBo.getLat(),
                                                postDetailBo.getLng()));
                                BaiduMapNavigation.openBaiduMapNavi(naviParaOption, RentDetailActivity.this);
                                break;
                            default:
                                snack("定位失败");
                                break;
                        }
                    }
                });
        atv_nav.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLocation();
            }
        });
        userInfo();
        bizUnit();
        mainRequest();
    }

    private void mainRequest() {
        postDetailApi.startRequest();
    }

    private void setData() {
        final RentalBo rentalBo = postDetailBo.getRentalBo();
        setToolbarTitle(postDetailBo.getPostDo().getCnEstate());
        atv_price.setText(PriceUtil.rentPrice(postDetailBo.getRentalPrice()));
        atv_pay_type.setText(rentalBo == null || TextUtils.isEmpty(rentalBo.getPayType()) ? "" : String.format(Locale.CHINA, "(%s)", rentalBo.getPayType()));
        if (rentalBo == null || TextUtils.isEmpty(rentalBo.getRentType())) {
            atv_rent_type.setVisibility(View.GONE);
        } else {
            atv_rent_type.setText(String.format(Locale.CHINA, "%s", rentalBo.getRentType()));
        }
        atv_house_type.setText(String.format(Locale.CHINA, "%d室%d厅", postDetailBo.getRoomCnt(), postDetailBo.getHallCnt()));
        atv_area.setText(String.format(Locale.CHINA, "%.0f平", postDetailBo.getGArea()));
        atv_floor.setText(postDetailBo.getFloor() == 0 ?
                String.format(Locale.CHINA, "%s/%d层", postDetailBo.getFloorDisplay(),
                        postDetailBo.getFloorTotal()) :
                String.format(Locale.CHINA, "%d/%d层", postDetailBo.getFloor(), postDetailBo.getFloorTotal()));
        atv_orientations.setText(postDetailBo.getDirection());
        atv_fitment.setText(postDetailBo.getFitment());
        atv_build_year.setText(String.format(Locale.CHINA, "%s", DateUtil.format(postDetailBo.getOpDate(),
                DateUtil.FORMAT1, DateUtil.FORMAT3)));
        atv_esf_estate.setText(postDetailBo.getCestName());
        atv_address.setText(String.format("%s-%s  %s", postDetailBo.getReginName(),
                postDetailBo.getBlockName(), postDetailBo.getDisplayAddress()));
        detailImgLayout.setTitle(postDetailBo.getTitle());
        detailImgLayout.setTencentVistaUrl(postDetailBo.getTencentVistaUrl());
        if (!TextUtils.isEmpty(postDetailBo.getRailWayName())) {
            if (vs_sale_metro != null) {
                vs_sale_metro.inflate();
                AppCompatTextView atv_metro_info = (AppCompatTextView) findViewById(R.id.atv_metro_info);
                if (atv_metro_info != null) {
                    atv_metro_info.setText(String.format(Locale.CHINA, "%s", CentaDistanceUtil.distanceOfPostAndMetro(postDetailBo.getRailLineNames(),
                            postDetailBo.getRailWayName(), postDetailBo.getRailWayDistance())));
                }
            }
        }

        atv_num_price.setText(String.format(Locale.CHINA, "%s套", postDetailBo.getPricePosts()));
        atv_num_nearby.setText(String.format(Locale.CHINA, "%s套", postDetailBo.getRoundPosts()));

        //配套设施
        final String serviceInfo = rentalBo == null ? null : rentalBo.getServiceInfo();
        final String applianceInfo = rentalBo == null ? null : rentalBo.getApplianceInfo();
        if (vs_appliance != null && (!TextUtils.isEmpty(serviceInfo) ||
                !TextUtils.isEmpty(applianceInfo))) {
            String combineInfo = serviceInfo + "," + applianceInfo;
            vs_appliance.inflate();
            FlowLayout flowLayout = (FlowLayout) findViewById(R.id.flowLayout);
            if (flowLayout != null) {
                if (combineInfo.contains(",")) {
                    String[] infos = combineInfo.split(",");
                    flowLayout.addTags(infos);
                } else {
                    flowLayout.addTag(combineInfo);
                }
            }
        }

        if (vs_tools != null) {
            vs_tools.inflate();
            detailToolsView = (DetailToolsView) findViewById(R.id.detailToolsView);
            consultView.setStaffs(postDetailBo.getStaffDos());
            consultView.setPostDetail(postDetailBo);
            if (detailToolsView != null) {
                detailToolsView.setStaffs(postDetailBo.getStaffDos());
                detailToolsView.setYueKanOnClick(new DetailToolsView.YueKanOnClick() {
                    @Override
                    public void gotoYueKanBill() {
                        gotoReservationBill();
                    }

                    @Override
                    public void addYueKan() {
                        addReservation();
                    }

                    @Override
                    public void consult() {
                        bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                    }
                });
            }
        }
        atv_map_name.setText(postDetailBo.getPostDo().getCnEstate());
        if (postDetailBo.getLat() != 0 &&
                postDetailBo.getLng() != 0) {
            img_arrow_address.setVisibility(View.VISIBLE);
            atv_nav.setVisibility(View.VISIBLE);
            rl_map.setVisibility(View.VISIBLE);
            GlideLoad.load(new GlideLoad.Builder(requestBuilder,
                    BdMapUtil.getBaiduMapImgUrl(postDetailBo.getLng(), postDetailBo.getLat()))
                    .placeHolder(R.drawable.ic_banner)
                    .error(R.drawable.ic_banner)
                    .openWifiSwitch()
                    .into(img_map));
        }

        invalidateOptionsMenu();

        otherRequest();

        reserveCount();

        RxDataBase.fpHistorySave(1, postId, postDetailBo.getPostDo())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<Void>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {

                    }
                });
    }

    /**
     * 其他数据请求
     */
    private void otherRequest() {
        RxRequest.postImg(RentDetailActivity.class, postId)
                .compose(this.<ArrayList<PostImgBo>>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<ArrayList<PostImgBo>>() {
                    @Override
                    public void call(ArrayList<PostImgBo> postImgBos) {
                        if (postImgBos != null) {
                            postImgBoArrayList.clear();
                            postImgBoArrayList.addAll(postImgBos);
                            imgList.clear();
                            imgListH.clear();
                            for (PostImgBo postImgBo : postImgBoArrayList) {
                                imgList.add(postImgBo.getPath());
                                imgListH.add(postImgBo.getHdPath());
                            }
                            detailImgLayout.setImgList(imgList);
                        }
                    }
                });
        collectStatus();
    }

    /**
     * 开始定位
     */
    private void startLocation() {
        showLoadingDialog();
        locationClient.start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_est_estate://小区
                if (postDetailBo != null)
                    startActivity(new Intent(this, EsfEstateDetailActivity.class)
                            .putExtra(ExtraConstant.CestCode, postDetailBo.getCestCode()));
                break;
            case R.id.rl_address://地图
            case R.id.img_map://地图
                if (postDetailBo == null ||
                        postDetailBo.getLat() == 0 || postDetailBo.getLng() == 0) {
                    snack("地理位置获取失败");
                } else {
                    startActivity(new Intent(this, AroundMapActivity.class)
                            .putExtra(ExtraConstant.LatLng, new LatLng(postDetailBo.getLat(), postDetailBo.getLng()))
                            .putExtra(ExtraConstant.MAP_NAME, postDetailBo.getCestName()));
                }
                break;
            case R.id.rl_esf_of_price:
                if (postDetailBo != null) {
                    startActivity(new Intent(this, EsfRentOfPriceActivity.class)
                            .putExtra(ExtraConstant.CestCode, postDetailBo.getCestCode())
                            .putExtra(ExtraConstant.Price, postDetailBo.getRentalPrice()));
                }
                break;
            case R.id.rl_esf_of_nearby:
                if (postDetailBo != null) {
                    startActivity(new Intent(this, EsfRentOfNearbyActivity.class)
                            .putExtra(ExtraConstant.Price, postDetailBo.getRentalPrice())
                            .putExtra(ExtraConstant.LatLng, new LatLng(postDetailBo.getLat(), postDetailBo.getLng())));
                }
                break;
            case R.id.overView:
                bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        reserveCount();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_collect_share, menu);
        MenuItem shareItem = menu.findItem(R.id.action_share);
        shareItem.setVisible(postDetailBo != null && !TextUtils.isEmpty(shareUrl));
        MenuItem collectItem = menu.findItem(R.id.action_collect);
        collectItem.setVisible(postDetailBo != null);
        collectItem.setIcon(collect ? R.drawable.ic_collected : R.drawable.ic_uncollected);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (R.id.action_collect == item.getItemId()) {
            collect();
        } else if (R.id.action_share == item.getItemId()) {
            if (shareDialog == null) {
                ShareBo shareBo = new ShareBo(1);
                shareBo.setHouseName(postDetailBo.getCestName());
                shareBo.setHouseDecription(postDetailBo.getTitle());
                shareBo.setHouseType(String.format(Locale.CHINA, "%d室%d厅",
                        postDetailBo.getRoomCnt(), postDetailBo.getHallCnt()));
                shareBo.setArea(String.format(Locale.CHINA, "%.0f平", postDetailBo.getGArea()));
                shareBo.setTotalPrice(String.format(Locale.CHINA, "%.0f元/月", postDetailBo.getRentalPrice()));
                shareBo.setHouseUrl(shareUrl.replace("{0}", postId));
                shareBo.setImageUrl(postDetailBo.getPostDo().getThumbPath());
                shareDialog = new ShareDialog(this, shareBo);
            }
            shareDialog.show();
            baiduEvent("E3_1_Type");
        }
        return super.onOptionsItemSelected(item);
    }

    private void collect() {
        if (AppConstant.IsLogin) {
            if (collect) {
                RxRequest.cancelCollect(RentDetailActivity.class, collectId)
                        .compose(this.<SimpleUserCenterRo>bindUntilEvent(ActivityEvent.DESTROY))
                        .subscribe(new Action1<SimpleUserCenterRo>() {
                            @Override
                            public void call(SimpleUserCenterRo simpleUserCenterRo) {
                                if (0 == simpleUserCenterRo.getResultNo()) {
                                    collect = false;
                                    EventBus.getDefault().post(new MineInfoUpdate(12));
                                    invalidateOptionsMenu();
                                    snack(R.string.collect_cancel);
                                } else {
                                    snack(simpleUserCenterRo.getMessage());
                                }
                            }
                        }, new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                netWorkUnable();
                            }
                        });
            } else {
                RxRequest.addCollect(RentDetailActivity.class, AppNameType.ESF, SourceType.ZUFANG, collectId, postId,
                        String.format(Locale.CHINA, "%s%s?postId=%s", AppConstant.SaleUrl, "Post", postId))
                        .compose(this.<SimpleUserCenterRo>bindUntilEvent(ActivityEvent.DESTROY))
                        .subscribe(new Action1<SimpleUserCenterRo>() {
                            @Override
                            public void call(SimpleUserCenterRo simpleUserCenterRo) {
                                if (0 == simpleUserCenterRo.getResultNo()) {
                                    collect = true;
                                    if (0 != simpleUserCenterRo.getResult()) {
                                        collectId = String.valueOf(simpleUserCenterRo.getResult());
                                    }
                                    EventBus.getDefault().post(new MineInfoUpdate(12));
                                    invalidateOptionsMenu();
                                    SprfUtil.setInt(RentDetailActivity.this,
                                            String.format("%s_%s", SprfConstant.COLLECT_POSITION, AppConstant.CityCode), 12);
                                    snack(R.string.collect_success);
                                } else {
                                    snack(simpleUserCenterRo.getMessage());
                                    collectStatus();
                                }
                            }
                        }, new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                netWorkUnable();
                            }
                        });
            }
        } else {
            startActivityForResult(new Intent(this, LoginActivity.class), CommonConstant.REQ_COLLECT);
        }
    }

    /**
     * 收藏状态
     */
    private void collectStatus() {
        if (AppConstant.IsLogin) {
            RxRequest.collectStatus(RentDetailActivity.class, postId,
                    String.format(Locale.CHINA, "%s%s?postId=%s", AppConstant.SaleUrl, "Post", postId))
                    .compose(this.<CollectInfoListRo>bindUntilEvent(ActivityEvent.DESTROY))
                    .subscribe(new Action1<CollectInfoListRo>() {
                        @Override
                        public void call(CollectInfoListRo collectInfoListRo) {
                            final ArrayList<CollectInfoBo> temp = collectInfoListRo.getList();
                            if (temp != null &&
                                    temp.size() > 0) {
                                collectId = String.valueOf(temp.get(0).getCollectID());
                                collect = !temp.get(0).isDel();
                            } else {
                                collect = false;
                            }
                            invalidateOptionsMenu();
                        }
                    });
        }
    }

    /**
     * 获取配置
     */
    private void bizUnit() {
        RxDataBase.getBizUnit()
                .compose(this.<BizUnitDo>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<BizUnitDo>() {
                    @Override
                    public void call(BizUnitDo bizUnitDo) {
                        consultView.setImEnable(bizUnitDo.isShowTalk());
                        shareUrl = bizUnitDo.getShareZufang();
                        invalidateOptionsMenu();
                    }
                });
    }

    /**
     * 用户信息
     */
    private void userInfo() {
        RxDataBase.getUser()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<UserDo>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<UserDo>() {
                    @Override
                    public void call(UserDo userDo) {
                        if (userDo != null)
                            userPhone = userDo.getPhone();
                        if (refreshTag == 1) {
                            addReservation();
                        } else if (refreshTag == 2) {
                            gotoReservationBill();
                        }
                    }
                });
    }

    /**
     * 添加约看
     */
    private void addReservation() {
        refreshTag = 1;
        if (AppConstant.IsLogin) {
            if (TextUtils.isEmpty(userPhone)) {
                startActivityForResult(new Intent(this, BindingPhoneActivity.class),
                        CommonConstant.REQ_BIND_MOBILE);
            } else {
                showLoadingDialog();
                RxRequest.addReservation(RentDetailActivity.class, "r", postDetailBo.getCestCode(), postDetailBo.getCestName(), postId)
                        .compose(this.<SimpleUserCenterRo>bindUntilEvent(ActivityEvent.DESTROY))
                        .subscribe(new Action1<SimpleUserCenterRo>() {
                                       @Override
                                       public void call(SimpleUserCenterRo simpleUserCenterRo) {
                                           cancelLoadingDialog();
                                           switch (simpleUserCenterRo.getResultNo()){
                                               case 0:
                                                   EventBus.getDefault().post(new ReserveUpdate(0));
                                                   reserveCount();
                                                   snack("已加入约看");
                                                   break;
                                               case -2:
                                                   snack("该房源已在您的约看单中");
                                                   break;
                                               case -3:
                                                   snack("约看单只能添加十套房源");
                                                   break;
                                               default:
                                                   snack(simpleUserCenterRo.getMessage());
                                                   break;
                                           }
                                       }
                                   }, new Action1<Throwable>()

                                   {
                                       @Override
                                       public void call(Throwable throwable) {
                                           netWorkUnable();
                                       }
                                   }

                        );
            }
        } else {
            startActivityForResult(new Intent(this, LoginActivity.class),
                    CommonConstant.REQ_BIND_MOBILE);
        }
    }

    /**
     * 查看约看单
     */

    private void gotoReservationBill() {
        refreshTag = 2;
        if (AppConstant.IsLogin) {
            if (TextUtils.isEmpty(userPhone)) {
                startActivityForResult(new Intent(RentDetailActivity.this, BindingPhoneActivity.class),
                        CommonConstant.REQ_BIND_MOBILE);
            } else {
                startActivity(new Intent(RentDetailActivity.this, ReservationListActivity.class)
                        .putExtra(ExtraConstant.EXTRA_POSITION, 0));
            }
        } else {
            startActivityForResult(new Intent(RentDetailActivity.this, LoginActivity.class),
                    CommonConstant.REQ_BIND_MOBILE);
        }
    }

    /**
     * 约看数量
     */
    private void reserveCount() {
        if (AppConstant.IsLogin) {
            RxRequest.reserveCount(getClass())
                    .compose(this.<ReservationRo>bindUntilEvent(ActivityEvent.DESTROY))
                    .subscribe(new Action1<ReservationRo>() {
                        @Override
                        public void call(ReservationRo reservationRo) {
                            if (detailToolsView != null) {
                                detailToolsView.setReserveCount(reservationRo.getTotal());
                            }
                        }
                    }, new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {
                            if (detailToolsView != null) {
                                detailToolsView.setReserveCount(0);
                            }
                        }
                    });
        }
    }

    @Subscribe
    public void onEventMainThread(ReserveUpdate reserveUpdate) {
        reserveCount();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CommonConstant.REQ_COLLECT:
                    collect();
                    break;
                case CommonConstant.REQ_BIND_MOBILE:
                    userInfo();
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK &&
                bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
            bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
